package com.yahoo.platform.yui.compressor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchEvent.Kind;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
import java.util.Queue;

import org.apache.log4j.Logger;

import com.yahoo.platform.util.DirHelper;
import com.yahoo.platform.util.ErrorTips;
import com.yahoo.platform.util.FileSystemEventArgs;

public class WebCompressor implements Observer {
	private static Logger logger = Logger.getLogger(WebCompressor.class);
	private String charset = "UTF-8";
	private int linebreakops = 8000;
	private Queue<File> folderList = null;
	private String srcRootFolder = null;
	private String dstRootFolder = null;

	public WebCompressor() {
		folderList = new LinkedList<File>();
	}

	public WebCompressor(String srcFolder, String dstFolder) {
		this.srcRootFolder = srcFolder;
		this.dstRootFolder = dstFolder;
		folderList = new LinkedList<File>();
	}

	public WebCompressor(String charset, int linebreakops) {
		this.charset = charset;
		this.linebreakops = linebreakops;
		folderList = new LinkedList<File>();
	}

	public void compress() {
		compress(srcRootFolder, dstRootFolder, true);
	}

	public void compress(String srcFolder, String dstFolder, boolean recursion) {
		File srcFile = new File(srcFolder);
		if (!srcFile.exists()) {
			System.out.printf(ErrorTips.errorDirectoryNotExist, srcFolder);
			return;
		}

		if (!srcFile.isDirectory()) {
			System.out.printf(ErrorTips.errorNotDirectory, srcFolder);
			return;
		}

		folderList.add(srcFile);
		String dstFile = dstFolder;
		JavaScriptHtmlCompositor javaScriptHtmlCompositor = new JavaScriptHtmlCompositor();
		CssCompressor cssCompressor = new CssCompressor(charset, linebreakops);
		int len = srcFolder.length();
		do {
			srcFile = folderList.remove();
			dstFile = dstFolder + srcFile.getAbsolutePath().substring(len);
			DirHelper.checkDir(dstFile);
			javaScriptHtmlCompositor.composite(srcFile.getAbsolutePath(),
					dstFile);
			cssCompressor.compressFolder(srcFile.getAbsolutePath(), dstFile);
			listFolder(srcFile);
			String exts = ".js,.css,.html";
			DirHelper.copyFolder(srcFile, dstFile, exts);
		} while (!folderList.isEmpty());
	}

	public void compress(String srcFile) {
		String cssExt = ".css";
		String jsExt = ".js";
		String htmlExt = ".html";

		File file = new File(srcFile);
		if (file.isDirectory())
			return;

		String dstFile = null;
		boolean success = false;
		if (srcFile.endsWith(cssExt)) {
			CssCompressor cssCompressor = new CssCompressor();
			dstFile = dstRootFolder + srcFile.replace(srcRootFolder, "");
			cssCompressor.compress(srcFile, dstFile);
		} else if (srcFile.endsWith(jsExt)) {
			dstFile = dstRootFolder + srcFile.replace(srcRootFolder, "");
			JavaScriptHtmlCompositor javaScriptHtmlCompositor = new JavaScriptHtmlCompositor(
					srcRootFolder, dstRootFolder);
			javaScriptHtmlCompositor.composite(srcFile);
		} else if (srcFile.endsWith(htmlExt)) {
			//String jsFileName = 
			JavaScriptHtmlCompositor javaScriptHtmlCompositor = new JavaScriptHtmlCompositor(
					srcRootFolder, dstRootFolder);
			String srcFolder = srcFile.substring(0, srcFile.lastIndexOf("\\"));
			javaScriptHtmlCompositor.composite(srcFolder, dstRootFolder);
		} else {
			dstFile = dstRootFolder + srcFile.replace(srcRootFolder, "");
			DirHelper.doCopy(srcFile, dstFile);
		}
		
		//logger.info("同步文件：" + dstFile);
	}

	public void addFolder(String srcFolder) {
		String dstFile = dstRootFolder + srcFolder.replace(srcRootFolder, "");
		DirHelper.checkDir(dstFile);
	}

	public void deleteFile(String srcFile) {
		String htmlExt = ".html";
		if (srcFile.endsWith(htmlExt)) {
			JavaScriptHtmlCompositor javaScriptHtmlCompositor = new JavaScriptHtmlCompositor(
					srcRootFolder, dstRootFolder);
			String srcFolder = srcFile.substring(0, srcFile.lastIndexOf("\\"));
			javaScriptHtmlCompositor.composite(srcFolder, dstRootFolder);
		} else {
			String dstFile = dstRootFolder + srcFile.replace(srcRootFolder, "");
			File file = new File(dstFile);
			if (file.isDirectory()) {
				DirHelper.deleFolder(dstFile);
				logger.info("同步删除目录：" + dstFile);
			} else {
				DirHelper.deleFile(dstFile);
				logger.info("同步删除文件：" + dstFile);
			}
		}
	}

	private void listFolder(File srcFile) {
		File[] files = srcFile.listFiles();
		for (File subFile : files) {
			if (subFile.isDirectory()) {
				folderList.add(subFile);
			}
		}
	}

	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		FileSystemEventArgs args = (FileSystemEventArgs) arg;
		Path path = args.getPath();
		@SuppressWarnings("rawtypes")
		Kind kind = args.getKind();
		switch (kind.name()) {
		case "ENTRY_CREATE":
			if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
				addFolder(path.toString());
			} else {

			}
			break;
		case "ENTRY_MODIFY":
			if(!Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)){
				compress(path.toString());
			}
			break;
		case "ENTRY_DELETE":
			deleteFile(path.toString());

			break;
		}

		// compress();
	}
}
